export const parseTitle = (compStyle) => {
  const result = {};
  result['show'] = !!compStyle['title.show'];
  addValue(result, 'text', compStyle['title.text']);
  addValue(result, 'left', compStyle['title.left']);

  const textStyle = {};
  addValue(textStyle, 'color', compStyle['title.textStyle.color']);
  addValue(textStyle, 'fontStyle', compStyle['title.textStyle.fontStyle']);
  addValue(textStyle, 'fontWeight', compStyle['title.textStyle.fontWeight']);
  addValue(textStyle, 'fontFamily', compStyle['title.textStyle.fontFamily']);
  addValue(textStyle, 'fontSize', compStyle['title.textStyle.fontSize']);
  result.textStyle = textStyle;

  return result;
};

export const parseTooltip = (compStyle) => {
  const result = {};
  result['show'] = !!compStyle['tooltip.show'];

  if (compStyle['tooltip.formatter']) {
    result['formatter'] = function(params) {
      return formatterTpl(params, compStyle['tooltip.formatter']);
    };
  }

  addValue(result, 'trigger', compStyle['tooltip.trigger']);
  addValue(result, 'backgroundColor', compStyle['tooltip.backgroundColor']);
  addValue(result, 'borderColor', compStyle['tooltip.borderColor']);
  addValue(result, 'confine', true);
  if (compStyle['tooltip.color']) {
    result['textStyle'] = { color: compStyle['tooltip.color'] };
  }
  return result;
};

/**
 * 折线图、柱状图、K线图 : {a}（系列名称），{b}（类目值），{c}（数值）, {d}（无）
 * 散点图 : {a}（系列名称），{b}（数据名称），{c}（数值数组）, {d}（无）
 * 地图 : {a}（系列名称），{b}（区域名称），{c}（合并数值）, {d}（无）
 * 饼图、仪表盘、漏斗图: {a}（系列名称），{b}（数据项名称），{c}（数值）, {d}（百分比）
 * 示例：{b0}: {c0}<br />{b1}: {c1}
 */
const formatterTpl = (params, template) => {
  if (!template) return '';

  const paramList = Array.isArray(params) ? params : [params];
  const valueMap = {
    'a': 'seriesName',
    'b': 'name',
    'c': 'value',
    'd': 'percent'
  };
  return template.replace(/\{([a-z])(\d*)}/g, function(match, key1, key2) {
    const dataIndex = parseInt(key2 || '0');
    if ((key2 || 0) >= paramList.length) return '--';

    if (key1 === 'c' && !key2) {
      if (paramList.length === 0) {
        const value = paramList[0][valueMap[key1]];
        return value || value === 0 ? value : '--';
      } else {
        const valueList = [];
        paramList.forEach(param => {
          const value = param[valueMap[key1]];
          if (value || value === 0) {
            valueList.push(value);
          }
        });
        return valueList;
      }
    } else {
      const value = paramList[dataIndex || 0][valueMap[key1 || 'a']];
      return value || value === 0 ? value : '--';
    }
  });
}

export const parseToolbox = (compStyle) => {
  return {
    show: !!compStyle['toolbox.show'],
    orient: compStyle['toolbox.orient'] || 'horizontal',
    itemSize: compStyle['toolbox.itemSize'] || 15,
    itemGap: compStyle['toolbox.itemGap'] || 8,
    feature: {
      dataView: {show: compStyle['toolbox.feature.dataView.show'], readOnly: false},
      magicType: {
        show: true,
        type: [
          compStyle['toolbox.feature.magicType.line'] ? 'line' : '',
          compStyle['toolbox.feature.magicType.bar'] ? 'bar' : '',
          compStyle['toolbox.feature.magicType.stack'] ? 'stack' : '',
        ]
      },
      restore: {show: compStyle['toolbox.feature.restore.show']},
      saveAsImage: {show: compStyle['toolbox.feature.saveAsImage.show']}
    }
  };
};

export const parseLegend = (compStyle, data) => {
  const result = {};

  result['show'] = !!compStyle['legend.show'];
  addValue(result, 'type', compStyle['legend.type']);
  addValue(result, 'orient', compStyle['legend.orient']);
  addValue(result, 'align', compStyle['legend.align']);
  addValue(result, 'top', compStyle['legend.top']);
  addValue(result, 'left', compStyle['legend.left']);
  addValue(result, 'width', compStyle['legend.width']);
  addValue(result, 'height', compStyle['legend.height']);
  addValue(result, 'itemSize', compStyle['legend.itemSize']);
  addValue(result, 'itemGap', compStyle['legend.itemGap']);
  addValue(result, 'icon', compStyle['legend.icon']);

  const textStyle = {};
  addValue(textStyle, 'color', compStyle['legend.textStyle.color']);
  addValue(textStyle, 'fontStyle', compStyle['legend.textStyle.fontStyle']);
  addValue(textStyle, 'fontWeight', compStyle['legend.textStyle.fontWeight']);
  addValue(textStyle, 'fontFamily', compStyle['legend.textStyle.fontFamily']);
  addValue(textStyle, 'fontSize', compStyle['legend.textStyle.fontSize']);
  result.textStyle = textStyle;
  result.data = data;

  return result;
};

export const parseAxis = (type, compStyle, dataList) => {
  const resultList = [];
  dataList.forEach(data => {
    const result = {type: compStyle[`${type}.type`]};
    if (compStyle[`${type}.type`] === 'category') {
      result['data'] = data;
      result['boundaryGap'] = !!compStyle[`${type}.boundaryGap`];
    }

    result['show'] = !!compStyle[`${type}.show`];
    result['axisLine'] = { show : !!compStyle[`${type}.axisLine`] };
    result['axisTick'] = {
      show : !!compStyle[`${type}.axisTick`],
      alignWithLabel: !!compStyle[`${type}.axisTick.alignWithLabel`]
    };
    result['splitLine'] = { show : !!compStyle[`${type}.splitLine`] };
    result['axisLabel'] = {
      show : !!compStyle[`${type}.axisLabel`],
      color: compStyle[`${type}.axisLabel.color`] || '',
      width: compStyle[`${type}.axisLabel.width`] || 500,
      rotate: compStyle[`${type}.axisLabel.rotate`] || 0,
      overflow: 'truncate',
    };

    if (compStyle[`${type}.type`] === 'value') {
      if (compStyle[`${type}.scale`]) {
        result['scale'] = true;
        result['min'] = null;
        result['max'] = null;
      } else {
        result['min'] = compStyle[`${type}.min`] || 0;
        if (compStyle[`${type}.max`]) {
          result['max'] = compStyle[`${type}.max`];
        }
      }
      if (compStyle[`${type}.splitNumber`]) {
        result['splitNumber'] = compStyle[`${type}.splitNumber`];
      }
    }

    resultList.push(result);
  });

  return resultList;
};

export const parseSeries = (option) => {
  if (option.type === 'line') {
    return parseSeriesLine(option);
  } else if (option.type === 'bar') {
    return parseSeriesBar(option);
  } else {
    return {};
  }
};

const parseSeriesLine = (option) => {
  const result = {};
  result['smooth'] = !!option['smooth'];
  result['showSymbol'] = !!option['showSymbol'];
  result['symbolSize'] = option['symbolSize'] || 4;
  result['symbol'] = option['symbol'] || 'none';
  result['lineStyle'] = { width: option['showLine'] ? (option['lineWidth'] || 2) : 0 };

  if (option['showArea']) {
    result['areaStyle'] = {
      origin: 'start',
      opacity: option['opacity'] || 0.7
    };
  }
  return result;
};

const parseSeriesBar = (option) => {
  const result = {};
  if (option['transparent']) {
    result['itemStyle'] = { color: 'transparent' };
  } else if (option['barWidth']) {
    result['barWidth'] = option['barWidth'];
  }
  if (option['label']) {
    result['label'] = { show: true };
  }
  return result;
};

const addValue = (data, field, value) => {
  if (typeof value !== 'undefined' && value !== null && value !== '') {
    data[field] = value;
  }
};

export default {
  parseToolbox,
  parseLegend,
  parseAxis,
  parseSeries
};